// Created by Muninn Group
// Version 1.2.1

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;


public class Convereter extends JFrame implements ActionListener{
	static ArrayList <Element> points;
	static DocumentBuilderFactory docFactory;
	static DocumentBuilder docBuilder;
	static Document doc;
	private static JPanel totalPane = new JPanel(new GridLayout(2, 1));
	private static JPanel fieldsPane = new JPanel(new GridLayout(0, 2));
	private static JPanel buttonPane = new JPanel();
	private static JTextField idField = new JTextField("C:/Users/admin/desktop/TCC.csv");
	private static JTextField codeField = new JTextField("C:/Users/admin/desktop/newfile.xml");
	private static JButton genL = new JButton("Convert");
	private static JButton exit = new JButton("Exit");

	private static int iid;
	private static int isystem;
	private static int iprefix;
	private static int isuffix;
	private static int itag;
	private static int idescription;
	private static int ifacet;
	private static int idec;
	private static int ipointtype;
	private static int ilolim;
	private static int ihilim;
	private static int ideadband;
	private static int itrend;
	private static int itype;
	private static int iparam;
	private static int icapacity;
	private static int iminroll;
	private static int imaxroll;
	private static int ialarm;
	private static int ialrmtype;
	private static int ialrmval;
	private static int ialrmdelay;
	private static int ialrmclass;
	private static int ilotxt;
	private static int ihitxt;
	private static int ioffnorm;
	
	private static int ilolimOU;
	private static int ihilimOU;
	private static int ideadbandOU;
	private static int ialarmOU;
	private static int ialrmtypeOU;
	private static int ialrmvalOU;
	private static int ialrmdelayOU;
	private static int ialrmclassOU;
	private static int ilotxtOU;
	private static int ihitxtOU;
	private static int ioffnormOU;
	
	private static int isuper;

	public static void main(String[] args) {
		new Convereter();
	}

	Convereter()
	{
		super("Converter v1.2.1");

		setSize(500, 125);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		Container con = getContentPane();
		con.add(totalPane);


		totalPane.add(fieldsPane);
		buttonPane.setAlignmentY(CENTER_ALIGNMENT);
		totalPane.add(buttonPane);

		fieldsPane.add(new JLabel("Input Table:"));
		fieldsPane.add(idField);
		fieldsPane.add(new JLabel("Output XML:"));
		fieldsPane.add(codeField);

		genL.setMnemonic('e');
		buttonPane.add(genL);
		genL.addActionListener(this);

		exit.setMnemonic('x');
		buttonPane.add(exit);
		exit.addActionListener(this);

		setVisible(true);
	}

	public void actionPerformed(ActionEvent event)
	{
		Object source = event.getSource();

		if (source == genL)
		{
			try {
				run();
			} catch (IOException e) {
				e.printStackTrace();
			}  
		}

		else if (source == exit)
			System.exit(EXIT_ON_CLOSE);
	}



	private static void run() throws IOException{
		docFactory = DocumentBuilderFactory.newInstance();
		try {
			docBuilder = docFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e2) {e2.printStackTrace();}
		doc = docBuilder.newDocument();

		BufferedReader br = null;
		points = new ArrayList<Element>(0);
		try {
			br = new BufferedReader(new FileReader(idField.getText()));
		} catch (FileNotFoundException e1) {e1.printStackTrace();}


		String sCurrentLine;
		sCurrentLine = br.readLine();
		String[] parts = sCurrentLine.split(",", -2);
		ArrayList<String> list = new ArrayList<String>();
		for(int i = 0; i < parts.length; i++){
			list.add(parts[i]);
			System.out.print(list.get(i)+" ");
		}
		iid 			= list.indexOf("ID");
		System.out.println(iid);
		isystem 		= list.indexOf("SYSTEM");
		System.out.println(isystem);
		iprefix 		= list.indexOf("PREFIX");
		System.out.println(iprefix);
		isuffix 		= list.indexOf("SUFFIX");
		System.out.println(isuffix );
		itag			= list.indexOf("TAG");
		System.out.println(itag	);
		idescription	= list.indexOf("DESCRIPTION");
		System.out.println(idescription);
		ifacet 			= list.indexOf("FACET");
		System.out.println(ifacet);
		idec 			= list.indexOf("DEC");
		System.out.println(idec );
		ipointtype 		= list.indexOf("POINT TYPE");
		System.out.println(ipointtype);
		ilolim 			= list.indexOf("LO LIM");
		System.out.println(ilolim );
		ihilim 			= list.indexOf("HI LIM");
		System.out.println(ihilim);
		ideadband 		= list.indexOf("DEADBAND");
		System.out.println(ideadband);
		itrend 			= list.indexOf("TREND");
		System.out.println(itrend);
		itype 			= list.indexOf("HIST TYPE");
		System.out.println(itype);
		iparam 			= list.indexOf("PARAM");
		System.out.println(iparam);
		icapacity 		= list.indexOf("CAPACITY");
		System.out.println(icapacity);
		iminroll 		= list.indexOf("MIN ROLL");
		System.out.println(iminroll);
		imaxroll 		= list.indexOf("MAX ROLL");
		System.out.println(imaxroll);
		ialarm 			= list.indexOf("ALARM");
		System.out.println(ialarm );
		ialrmtype		= list.indexOf("ALARM TYPE");
		System.out.println(ialrmtype);
		ialrmval		= list.indexOf("VAL");
		System.out.println(ialrmval);
		ialrmdelay		= list.indexOf("DELAY");
		System.out.println(ialrmdelay);
		ialrmclass		= list.indexOf("CLASS");
		System.out.println(ialrmclass);
		ilotxt 			= list.indexOf("LO TXT");
		System.out.println(ilotxt);
		ihitxt 			= list.indexOf("HI TXT");
		System.out.println(ihitxt);
		ioffnorm 		= list.indexOf("OFF NORM TXT");
		System.out.println(ioffnorm);
		
		ilolimOU 			= list.indexOf("OU LO LIM");
		System.out.println(ilolimOU );
		ihilimOU 			= list.indexOf("OU HI LIM");
		System.out.println(ihilimOU);
		ideadbandOU 		= list.indexOf("OU DEADBAND");
		System.out.println(ideadbandOU);
		ialarmOU 			= list.indexOf("OU ALARM");
		System.out.println(ialarmOU );
		ialrmtypeOU		= list.indexOf("OU ALARM TYPE");
		System.out.println(ialrmtypeOU);
		ialrmvalOU		= list.indexOf("OU VAL");
		System.out.println(ialrmvalOU);
		ialrmdelayOU		= list.indexOf("OU DELAY");
		System.out.println(ialrmdelayOU);
		ialrmclassOU		= list.indexOf("OU CLASS");
		System.out.println(ialrmclassOU);
		ilotxtOU 			= list.indexOf("OU LO TXT");
		System.out.println(ilotxtOU);
		ihitxtOU 			= list.indexOf("OU HI TXT");
		System.out.println(ihitxtOU);
		ioffnormOU 		= list.indexOf("OU OFF NORM TXT");
		System.out.println(ioffnormOU);
		
		isuper 			= list.indexOf("SUPER");
		System.out.println(isuper);
		sCurrentLine = br.readLine();
		while (sCurrentLine != null) {
			parse(sCurrentLine);
			sCurrentLine = br.readLine();
		}
		if (br != null) br.close();

		try {

			Element rootElement = doc.createElement("tag");
			doc.appendChild(rootElement);

			for(int i = 0; i < points.size(); i++){
				rootElement.appendChild(points.get(i));
			}

			// write the contents into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			DOMSource source = new DOMSource(doc);
			StreamResult result = new StreamResult(new File(codeField.getText()));

			transformer.transform(source, result);

			System.out.println("File saved!");

		} catch (TransformerException tfe) {
			tfe.printStackTrace();
		}
	}

	private static void parse(String sCurrentLine) {
		String[] parts = sCurrentLine.split(",", -2);
		if(parts.length-1==sCurrentLine.length()){ return; }
		String sid = ""; 			
		String ssystem = ""; 		
		String sprefix = ""; 	
		String ssuffix = ""; 
		String stag = ""; 			
		String sdescription = ""; 	
		String sfacet = ""; 	
		String sdec = ""; 
		String spointtype = ""; 	
		String slolim = ""; 	
		String shilim = ""; 
		String sdeadband = "";
		String strend = ""; 		 
		String stype = ""; 		
		String sparam = ""; 	
		String scapacity = ""; 	
		String sminroll = ""; 		
		String smaxroll = ""; 	
		String salarm = "";  
		String salrmtype = "";
		String salrmval = "";
		String salrmdelay = "";
		String salrmclass = "";
		String slotxt = ""; 	
		String shitxt = ""; 
		String soffnorm = "";
		
		String slolimOU = ""; 	
		String shilimOU = ""; 
		String sdeadbandOU = "";
		String salarmOU = "";  
		String salrmtypeOU = "";
		String salrmvalOU = "";
		String salrmdelayOU = "";
		String salrmclassOU = "";
		String slotxtOU = ""; 	
		String shitxtOU = ""; 
		String soffnormOU = "";
		
		String ssuper = "";  

		try{ if(iid>=0){			Integer.parseInt(parts[iid]);		sid = parts[iid];}						} catch(Exception e){}
		try{ if(isystem>=0){											ssystem = parts[isystem];}				} catch(Exception e){}
		try{ if(iprefix>=0){											sprefix = parts[iprefix];}				} catch(Exception e){}
		try{ if(isuffix>=0){											ssuffix = parts[isuffix];}				} catch(Exception e){}
		try{ if(itag>=0){												stag = parts[itag];}					} catch(Exception e){}
		try{ if(idescription>=0){										sdescription = parts[idescription];}	} catch(Exception e){}
		try{ if(ifacet>=0){												sfacet = parts[ifacet];}				} catch(Exception e){}
		try{ if(idec>=0){			Integer.parseInt(parts[idec]);		sdec = parts[idec];}					} catch(Exception e){}
		try{ if(ipointtype>=0){											spointtype = parts[ipointtype];}		} catch(Exception e){}
		try{ if(ilolim>=0){			Integer.parseInt(parts[ilolim]);	slolim = parts[ilolim];}				} catch(Exception e){}
		try{ if(ihilim>=0){			Integer.parseInt(parts[ihilim]);	shilim = parts[ihilim];}				} catch(Exception e){}
		try{ if(ideadband>=0){		Integer.parseInt(parts[ideadband]);	sdeadband = parts[ideadband];}			} catch(Exception e){}
		try{ if(itrend>=0){												strend = parts[itrend];}				} catch(Exception e){}
		try{ if(itype>=0){												stype = parts[itype];}					} catch(Exception e){}
		try{ if(iparam>=0){			Integer.parseInt(parts[iparam]);	sparam = parts[iparam];}				} catch(Exception e){}
		try{ if(icapacity>=0){		Integer.parseInt(parts[icapacity]);	scapacity = parts[icapacity];}			} catch(Exception e){}
		try{ if(iminroll>=0){		Integer.parseInt(parts[iminroll]);	sminroll = parts[iminroll];}			} catch(Exception e){}
		try{ if(imaxroll>=0){		Integer.parseInt(parts[imaxroll]);	smaxroll = parts[imaxroll];}			} catch(Exception e){}
		try{ if(ialarm>=0){												salarm = parts[ialarm];}				} catch(Exception e){}
		try{ if(ialrmtype>=0){											salrmtype = parts[ialrmtype];}			} catch(Exception e){}
		try{ if(ialrmval>=0){											salrmval = parts[ialrmval];}			} catch(Exception e){}
		try{ if(ialrmdelay>=0){		Integer.parseInt(parts[ialrmdelay]);salrmdelay = parts[ialrmdelay];}		} catch(Exception e){}
		try{ if(ialrmclass>=0){											salrmclass = parts[ialrmclass];}		} catch(Exception e){}
		try{ if(ilotxt>=0){												slotxt = parts[ilotxt];}				} catch(Exception e){}
		try{ if(ihitxt>=0){												shitxt = parts[ihitxt];}				} catch(Exception e){}
		try{ if(ioffnorm>=0){											soffnorm = parts[ioffnorm];}			} catch(Exception e){}
		
		try{ if(ilolimOU>=0){			Integer.parseInt(parts[ilolimOU]);		slolimOU = parts[ilolimOU];}				} catch(Exception e){}
		try{ if(ihilimOU>=0){			Integer.parseInt(parts[ihilimOU]);		shilimOU = parts[ihilimOU];}				} catch(Exception e){}
		try{ if(ideadbandOU>=0){		Integer.parseInt(parts[ideadbandOU]);	sdeadbandOU = parts[ideadbandOU];}			} catch(Exception e){}
		try{ if(ialarmOU>=0){													salarmOU = parts[ialarmOU];}				} catch(Exception e){}
		try{ if(ialrmtypeOU>=0){												salrmtypeOU = parts[ialrmtypeOU];}			} catch(Exception e){}
		try{ if(ialrmvalOU>=0){													salrmvalOU = parts[ialrmvalOU];}			} catch(Exception e){}
		try{ if(ialrmdelayOU>=0){		Integer.parseInt(parts[ialrmdelayOU]);	salrmdelayOU = parts[ialrmdelayOU];}		} catch(Exception e){}
		try{ if(ialrmclassOU>=0){												salrmclassOU = parts[ialrmclassOU];}		} catch(Exception e){}
		try{ if(ilotxtOU>=0){													slotxtOU = parts[ilotxtOU];}				} catch(Exception e){}
		try{ if(ihitxtOU>=0){													shitxtOU = parts[ihitxtOU];}				} catch(Exception e){}
		try{ if(ioffnormOU>=0){													soffnormOU = parts[ioffnormOU];}			} catch(Exception e){}
		
		try{ if(isuper>=0){												ssuper = parts[isuper];}				} catch(Exception e){}

		
		if(stag.equals("")) return;
		Element point = doc.createElement("point");
		point.setAttribute("name", stag);

		Element hist = doc.createElement("hist");
		Element alrm = doc.createElement("alrm");
		Element OUalrm = doc.createElement("alrmOU");
		
		boolean goodhist = true;

		if(strend.indexOf("X")>=0){
			Element etrend = doc.createElement("trend");
			if(stype.indexOf("I")>=0){
				try{
					if((sparam.isEmpty()&&scapacity.isEmpty())){
						goodhist = false;
					}
				}catch(Exception e){goodhist = false;}
				etrend.setAttribute("type", "int");
				etrend.setAttribute("v", sparam);
			}
			else if(stype.indexOf("C")>=0){
				try{
					if(scapacity.isEmpty()||(sparam.isEmpty()&&spointtype.indexOf('N')>=0)){
						goodhist = false;
					}
				}catch(Exception e){goodhist = false;}
				etrend.setAttribute("type", "cov");
				etrend.setAttribute("v", sparam);
			}
			else{
				goodhist = false;
			}

			Element cap = doc.createElement("cap");
			cap.setAttribute("v", scapacity);
			Element max = doc.createElement("max");
			max.setAttribute("v", smaxroll);
			Element min = doc.createElement("min");
			min.setAttribute("v", sminroll);
			Element facet = doc.createElement("facets");
			facet.setAttribute("v", sfacet);
			Element precision = doc.createElement("precision");
			precision.setAttribute("v", sdec);
			hist.appendChild(etrend);
			if(!scapacity.isEmpty()){
				hist.appendChild(cap);
			}
			if(!smaxroll.isEmpty()){
				hist.appendChild(max);
			}
			if(!sminroll.isEmpty()){
				hist.appendChild(min);
			}
			if(!sfacet.isEmpty()){
				hist.appendChild(facet);
			}
			if(!sdec.isEmpty()){
				hist.appendChild(precision);
			}
			if(goodhist){
				point.appendChild(hist);
			}
		}
		//--------------------------------------------------
		//----------ALARMS----------------------------------
		boolean goodalarm = true;
		if(salarm!=null){
			if(spointtype.toLowerCase().indexOf("b")>=0){
				if(!salrmtype.equals("cos")&&!salrmtype.equals("cf")){
					goodalarm = false;
				}
				Element etype = doc.createElement("type");
				etype.setAttribute("t", salrmtype);
				Element eval = doc.createElement("val");
				eval.setAttribute("v", salrmval);
				alrm.appendChild(etype);
				alrm.appendChild(eval);
			}
			else if(spointtype.toLowerCase().indexOf("e")>=0){
				if((!salrmtype.equals("cos")&&!salrmtype.equals("cf"))){
					goodalarm = false;
				}
				if(salrmtype.equals("cos")){
					String[] vals = salrmval.split(";");
					for(int i = 0; i < vals.length; i++){
						if(sfacet.indexOf(vals[i].trim())<0){
							goodalarm=false;
						}
					}
				}
				Element etype = doc.createElement("type");
				etype.setAttribute("t", salrmtype);
				Element eval = doc.createElement("val");
				eval.setAttribute("v", salrmval);
				alrm.appendChild(etype);
				alrm.appendChild(eval);
			}
			else if(spointtype.toLowerCase().indexOf("n")>=0&&!(shilim.isEmpty()||slolim.isEmpty())){
				Element ehigh = doc.createElement("high");
				ehigh.setAttribute("v", shilim);
				ehigh.setAttribute("text", shitxt);
				Element elow = doc.createElement("low");
				elow.setAttribute("v", slolim);
				elow.setAttribute("text", slotxt);
				alrm.appendChild(elow);
				alrm.appendChild(ehigh);
			}
			else{
				goodalarm = false;
			}
			
			Element edelay = doc.createElement("delay");
			edelay.setAttribute("v", salrmdelay);
			Element eclass = doc.createElement("class");
			eclass.setAttribute("c", salrmclass);
			Element eoffnorm = doc.createElement("offnorm");
			eoffnorm.setAttribute("text", soffnorm);
			Element deadband = doc.createElement("deadband");
			deadband.setAttribute("v", sdeadband);
			
			if(!sdeadband.isEmpty()){
				alrm.appendChild(deadband);
			}
			if(!salrmdelay.isEmpty()){
				alrm.appendChild(edelay);
			}
			else{
				edelay.setAttribute("v", "0");
				alrm.appendChild(edelay);
			}
			if(!salrmclass.isEmpty()){
				alrm.appendChild(eclass);
			}
			else{
				eclass.setAttribute("c", "DefaultAlarmClass");
				alrm.appendChild(eclass);
			}
			if(!soffnorm.isEmpty()){
				alrm.appendChild(eoffnorm);
			}
			else{
				eoffnorm.setAttribute("text", "has transistioned to an offnormal value. THIS NEEDS CHANGED-------------------------------------------OFF NORMAL TEXT");
				alrm.appendChild(eoffnorm);
			}
			if(goodalarm)
				point.appendChild(alrm);
		}
		if(point.getChildNodes().getLength()>0&&isValid(point)){
			points.add(point);
		}
		
//--------------------------------------------- OHIO U ALARMS ---------------------------------------------
		goodalarm = true;
		if(salarmOU!=null){
			if(spointtype.toLowerCase().indexOf("b")>=0){
				if(!salrmtypeOU.equals("cos")&&!salrmtypeOU.equals("cf")){
					goodalarm = false;
				}
				Element etype = doc.createElement("type");
				etype.setAttribute("t", salrmtypeOU);
				Element eval = doc.createElement("val");
				eval.setAttribute("v", salrmvalOU);
				OUalrm.appendChild(etype);
				OUalrm.appendChild(eval);
			}
			else if(spointtype.toLowerCase().indexOf("e")>=0){
				if((!salrmtypeOU.equals("cos")&&!salrmtypeOU.equals("cf"))){
					goodalarm = false;
				}
				if(salrmtypeOU.equals("cos")){
					String[] vals = salrmvalOU.split(";");
					for(int i = 0; i < vals.length; i++){
						if(sfacet.indexOf(vals[i].trim())<0){
							goodalarm=false;
						}
					}
				}
				Element etype = doc.createElement("type");
				etype.setAttribute("t", salrmtypeOU);
				Element eval = doc.createElement("val");
				eval.setAttribute("v", salrmvalOU);
				OUalrm.appendChild(etype);
				OUalrm.appendChild(eval);
			}
			else if(spointtype.toLowerCase().indexOf("n")>=0&&!(shilimOU.isEmpty()||slolimOU.isEmpty())){
				Element ehigh = doc.createElement("high");
				ehigh.setAttribute("v", shilimOU);
				ehigh.setAttribute("text", shitxtOU);
				Element elow = doc.createElement("low");
				elow.setAttribute("v", slolimOU);
				elow.setAttribute("text", slotxtOU);
				OUalrm.appendChild(elow);
				OUalrm.appendChild(ehigh);
			}
			else{
				goodalarm = false;
			}
			
			Element edelay = doc.createElement("delay");
			edelay.setAttribute("v", salrmdelayOU);
			Element eclass = doc.createElement("class");
			eclass.setAttribute("c", salrmclassOU);
			Element eoffnorm = doc.createElement("offnorm");
			eoffnorm.setAttribute("text", soffnormOU);
			Element deadband = doc.createElement("deadband");
			deadband.setAttribute("v", sdeadbandOU);
			
			if(!sdeadbandOU.isEmpty()){
				OUalrm.appendChild(deadband);
			}
			if(!salrmdelayOU.isEmpty()){
				OUalrm.appendChild(edelay);
			}
			else{
				edelay.setAttribute("v", "0");
				OUalrm.appendChild(edelay);
			}
			if(!salrmclassOU.isEmpty()){
				OUalrm.appendChild(eclass);
			}
			else{
				eclass.setAttribute("c", "DefaultAlarmClass");
				OUalrm.appendChild(eclass);
			}
			if(!soffnormOU.isEmpty()){
				OUalrm.appendChild(eoffnorm);
			}
			else{
				eoffnorm.setAttribute("text", "has transistioned to an offnormal value. THIS NEEDS CHANGED-------------------------------------------OFF NORMAL TEXT");
				OUalrm.appendChild(eoffnorm);
			}
			if(goodalarm)
				point.appendChild(OUalrm);
		}
		if(point.getChildNodes().getLength()>0&&isValid(point)){
			points.add(point);
		}

	}

	private static boolean isValid(Element point) {
		return true;
	}



}
